﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CashOrCard.Helper;
using CashOrCard.Models;
using CashOrCard.Repository;
using CashOrCard.Extensions;

namespace CashOrCard.Controllers
{
    
    public class UserController : Controller
    {
        private readonly IBaseRepository<User> _userRep;
        private readonly IBaseRepository<Role> _roleRep;
        public UserController(IBaseRepository<User> userRep,IBaseRepository<Role> roleRep)
        {
            this._userRep = userRep;
            this._roleRep = roleRep;
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "usermanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult Index()
        {
            return View();
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "usermanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult GetAllUsers(User uinfo)
        {
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            string strSort = Request["sort"] == null ? "" : Request["sort"].ToString();
            string strOrder = Request["order"] == null ? "asc" : Request["order"].ToString();
            int total = 0;
            IQueryable<User> users;
            if (string.IsNullOrEmpty(strSort))
            {
                users = _userRep.LoadPagerEntities(pageSize, pageIndex, out total, x => (string.IsNullOrEmpty(uinfo.FirstName) || x.FirstName.ToLower().Contains(uinfo.FirstName.ToLower()))
                                                                                             && (uinfo.RoleId == 0 || x.RoleId == uinfo.RoleId)
                                                                                             && x.IsEnable, true, x => x.UserId);
            }
            else
            {
                users = _userRep.LoadPagerEntities(pageSize, pageIndex, out total, x => (string.IsNullOrEmpty(uinfo.FirstName) || x.FirstName.ToLower().Contains(uinfo.FirstName.ToLower()))
                                                                                             && (uinfo.RoleId == 0 || x.RoleId == uinfo.RoleId)
                                                                                             && x.IsEnable, strOrder.Equals("asc"), x => x.RoleId);
            }
            var list = (from user in users
                         select new
                         {
                             UserId = user.UserId,
                             Email = user.Email,
                             FirstName = user.FirstName,
                             LastName = user.LastName,
                             ZipCode = user.ZipCode,
                             CompanyName = user.CompanyName, 
                             PrimaryPhoneNumber = user.PrimaryPhoneNumber,
                             AltPhoneNumber = user.AltPhoneNumber,
                             CreateDate = user.CreateDate,
                             RoleId = user.RoleId,
                             //Password = user.Password,
                             RoleName = user.Role.RoleName
                         }).ToList();

            var result = new { total = total, rows = list};

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "usermanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult AddNewUser(User uinfo)
        {
            string message = string.Empty;
            bool added = false;
            if(_userRep.LoadEntities(x => x.Email.ToLower() == uinfo.Email.ToLower()).Count() > 0)
            {
                message = "Existed Email, Please use another one";
            }
            else
            {
                uinfo.CreateDate = DateTime.Now;
                uinfo.IsApproved = true;
                uinfo.IsEnable = true;
                uinfo.Password = HashUtility.GetMD5HashData(uinfo.Password);
                added = _userRep.AddEntities(uinfo);
                if (added)
                    message = "User add successfully";
                else
                    message = "Some errors occured, please contact admin for suporting";
            }
            return Json(new { Success = added, Message = message });
        }

        public ActionResult GetRoles()
        {
            var roleList = from roles in _roleRep.LoadEntities(x => true)
                           select new { RoleId = roles.RoleId, RoleName = roles.RoleName };
            return Json(roleList);
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "usermanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult UpdateUser(User uinfo)
        {
            string message = string.Empty;
            bool updated = false;
            var user = _userRep.Get(uinfo.UserId);
            user.FirstName = uinfo.FirstName;
            user.LastName = uinfo.LastName;
            user.CompanyName = uinfo.CompanyName;
            user.ZipCode = uinfo.ZipCode;
            user.PrimaryPhoneNumber = uinfo.PrimaryPhoneNumber;
            user.AltPhoneNumber = uinfo.AltPhoneNumber;
            if(!string.IsNullOrEmpty(uinfo.Password))
            {
                user.Password = HashUtility.GetMD5HashData(uinfo.Password);
            } 
            updated = _userRep.UpdateEntities(user);
            TempData["uId"] = uinfo.UserId;
            if (updated)
                message = "User edit successfully";
            else
                message = "Some errors occured, please contact admin for suporting";
            return Json(new { Success = updated, Message = message });
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "usermanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult DeleteUser(int id)
        {
            var user = _userRep.Get(id);
            user.IsEnable = false;
            var result = _userRep.UpdateEntities(user);
            if (result)
                return Content("success");
            else
                return Content("Some errors occured.");
        }
        
        public ActionResult MyProfile()
        {
            TempData["uId"] = Common.CurrentUser.UserId;
            return View();
        }

        public ActionResult GetUserById(int id)
        {
            var temp = _userRep.Get(id);
            var user = new User{ 
                                    UserId = temp.UserId,
                                    FirstName = temp.FirstName,
                                    LastName = temp.LastName,
                                    Email = temp.Email,
                                    CompanyName = temp.CompanyName,
                                    ZipCode = temp.ZipCode,
                                    PrimaryPhoneNumber = temp.PrimaryPhoneNumber,
                                    AltPhoneNumber = temp.AltPhoneNumber
                               };
            ViewBag.User = user;
            return Json(user, JsonRequestBehavior.AllowGet);
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "password_access", ErrorView = "PermissionDenied")]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "password_access", ErrorView = "PermissionDenied")]
        public ActionResult SavePassword(string curPsd, string newPsd)
        {

            string email = Common.CurrentUserEamil;
            bool success;
            string message = string.Empty;
            var curUser = _userRep.LoadEntities(x => x.Email == email && x.IsEnable == true).FirstOrDefault();
            if (HashUtility.ValidateMD5HashData(curPsd, curUser.Password))
            {
                curUser.Password = HashUtility.GetMD5HashData(newPsd);
                success = _userRep.UpdateEntities(curUser);
                message = "Password changed";
            }
            else
            {
                success = false;
                message = "Password is invalid";
            }
            return Json(new { Success = success, Message = message });
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "recharge_access", ErrorView = "PermissionDenied")]
        public ActionResult Recharge()
        {
            return View();
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "recharge_access", ErrorView = "PermissionDenied")]
        public ActionResult SaveAmount(string amount)
        {
            var user = Common.CurrentUser;
            user.Amount = decimal.Parse(amount);
            var result = _userRep.UpdateEntities(user);
            if (result)
                return Content("success");
            else
                return Content("Some errors occured.");
        }
        
    }
}
